from django.shortcuts import render, redirect
from TestingPlatform import models
from TestingPlatform.utils.pagination import Pagination
from TestingPlatform.utils.form import UserModelForm


def user_list(request):
    """ 用户管理 """
    userId = request.session["info"]["id"]

    queryset = models.JD_Account.objects.all().filter(user_id=userId)

    page_object = Pagination(request, queryset, page_size=2)
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, 'SystemManagement/user/user_list.html', context)


def user_add(request):
    """ 添加用户（ModelForm版本）"""
    userId = request.session["info"]["id"]

    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'SystemManagement/user/user_add.html', {"form": form})

    # 用户POST提交数据，数据校验。
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.instance.user_id = userId
        form.save()
        return redirect('/user/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'SystemManagement/user/user_add.html', {"form": form})


def user_edit(request, nid):
    """ 编辑用户 """
    row_object = models.JD_Account.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = UserModelForm(instance=row_object)
        return render(request, 'SystemManagement/user/user_edit.html', {'form': form})

    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据，如果想要再用户输入以外增加一点值
        form.save()
        return redirect('/user/list/')
    return render(request, 'SystemManagement/user/user_edit.html', {"form": form})


def user_delete(request, nid):
    row_object = models.JD_Account.objects.get(id=nid)
    row_object.del_flag = 1
    row_object.save()
    return redirect('/user/list/')
